package com.itboye.ihomebank.activity.keytwo;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.itboye.ihomebank.KeyFragment;
import com.itboye.ihomebank.MainActivity;
import com.itboye.ihomebank.R;

import com.itboye.ihomebank.activity.guanjia.ActivityGuanJia;
import com.itboye.ihomebank.activity.key.ActivitySheBei;
import com.itboye.ihomebank.activity.login.LoginActivity;
import com.itboye.ihomebank.activity.me.ActivityMyData;
import com.itboye.ihomebank.activity.qianyue.ActivityMySign;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.KeysBean;
import com.itboye.ihomebank.bean.RedDotBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SIDBean;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.presenter.KeyTwoPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.ttKey.DaoMaster;
import com.itboye.ihomebank.ttKey.DaoSession;
import com.itboye.ihomebank.ttKey.DbService;
import com.itboye.ihomebank.ttKey.Key;
import com.itboye.ihomebank.ttKey.KeyDao;
import com.itboye.ihomebank.ttKey.MyPreference;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.ListDialog;
import com.itboye.ihomebank.util.MyGongJv;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimesUtils;
import com.itboye.ihomebank.util.broad.BroadEnum;
import com.itboye.ihomebank.util.broad.RedDotEnum;
import com.itboye.ihomebank.util.controller.LoginController;
import com.itboye.ihomebank.util.controller.UnLoginState;
import com.itboye.ihomebank.web.WebActivity;
import com.sitri.sdk.SLock;
import com.sitri.sdk.callback.visible.CommonCallback;
import com.sitri.sdk.callback.visible.UnlockCallback;
import com.sitri.sdk.model.ID;
import com.sitri.sdk.model.ResultData;
import com.sitri.sdk.model.ResultError;
import com.sitri.sdk.model.lock.LockMode;

import org.greenrobot.greendao.database.Database;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import static com.itboye.ihomebank.activity.key.ActivitySheBei.adminKeyboardPwd;
import static com.itboye.ihomebank.activity.key.ActivitySheBei.adminPs;
import static com.itboye.ihomebank.activity.key.ActivitySheBei.unlockKey;
import static com.itboye.ihomebank.base.MyApplcation.getStringContent;
import static com.itboye.ihomebank.util.MyGongJv.setButtonFocusChanged;
import static com.itboye.ihomebank.util.SPUtils.get;
import static java.lang.Long.parseLong;

/**
 * 白马门锁-管理员界面
 */
public class KeyGuanLiActivity extends BaseOtherActivity implements CommonCallback, Observer {
    View v_statusbar;
    ImageView key_finish;// 返回
    TextView key_title;// 标题
    ImageView key_shezhi;// 设置
    ImageButton icon;// 开锁
    LinearLayout key_send_key, key_send_pass, key_user, key_jilu;//发送钥匙，发送密码，用户管理，开锁记录
    TextView key_tv_mess, key_tv_jiaozu, key_tv_weixiu, key_tv_zhangdan;//消息，交租，维修，账单
    ImageView key_img_mess, key_img_jiaozu, key_img_weixiu, key_img_zhangdan;//消息，交租，维修，账单消息 红点显示
    private Key localKey;
    String uid;
    KeyTwoPresenter keyPresenter;
    PopupWindow popupWindow;

    String cy_mac = "";
    private List<KeysBean> kensBean;//钥匙列表数据
    private List<Key> keys;//本地缓存的钥匙
    public static DaoSession daoSession;
    public static KeyDao keyDao;
    String activity = "";//是从哪条转过来的，钥匙界面，还是从主界面跳转过来的常用锁

    int activityType=0;//2 是否是从闪屏页调转过来的   其他
    ToggleButton key_tb;//声音开关
    String key_play = "";

    String leixing = "";
    LinearLayout bottom2, bottom3;//管理钥匙（管理员和租户显示），时间限制（普通用户显示）
    TextView key_send;//管理员显示发送密码，租户显示设置密码
    TextView shijain_start, shijain_end;//开始时间，结束时间
    int power;//电量

    private static final int REQUEST_CODE_PERMISSION = 1000;

    public static String KAIMEN = "menkaile";//门开了的广播

    HousePresenter mHousePresenter;
    public static String device_token;
    ListDialog mShenQin,mQianDing,mFujian,mYuQi;
    String sid;
    int cz;

  //  Animation rotate;
    @Override
    protected int layout_id() {
        return R.layout.activity_guan_li_key2;
    }

    @Override
    protected void onInitController() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        SLock.getServices().setCommonCallback(this);
    }

    @Override
    protected void onInit() {
        SLock.getServices().setIsDebug(true);
        SLock.getServices().setCommonCallback(this);
        clear();
        sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";

        Glide.with(KeyGuanLiActivity.this).load(R.drawable.guansuo)
                .diskCacheStrategy(DiskCacheStrategy.ALL).into(icon);
        keyPresenter = new KeyTwoPresenter(this);
        mHousePresenter=new HousePresenter(this);
        uid = get(this, null, SPContants.USER_ID, "") + "";

        cy_mac = (String) SPUtils.get(MyApplcation.ctx, null, SPContants.CHANGYONG_MAC, "");
        key_play = (String) SPUtils.get(MyApplcation.ctx, null, SPContants.KEY_PLAY, "");
        if (key_play.equals("1")) {
            key_tb.setChecked(false);
        } else {
            key_tb.setChecked(true);
        }
        activity = getIntent().getStringExtra("activity");
        leixing = getIntent().getStringExtra("leixing");
        activityType=getIntent().getIntExtra("Tankuang",0);
        //是否弹出弹框 (首次启动的界面)
        if (activityType==2){
            activityType=0;
            if (!"".equals(SPUtils.get(MyApplcation.ctx,null,SPContants.USER_ID,"386")+"")){
                mHousePresenter.queryRedDot(SPUtils.get(MyApplcation.ctx,null,SPContants.USER_ID,"386")+"",MyApplcation.device_token);
            }
        }else {
            //红点显示
            //消息
            updateRedDot(key_img_mess, (Integer) SPUtils.get(getApplication(),null,SPContants.TOTAL_MESSAGE,0));
            //交租
            updateRedDot(key_img_jiaozu,(Integer) SPUtils.get(getApplication(),null,SPContants.YUQI_COUNT,0));
            //维修
            updateRedDot(key_img_weixiu,(Integer) SPUtils.get(getApplication(),null,SPContants.REPAIR_COUNT,0));
            //账单
            updateRedDot(key_img_zhangdan,(Integer) SPUtils.get(getApplication(),null,SPContants.BILL_COUNT,0));
        }

        if (leixing.equals("0")) {//管理员
            bottom2.setVisibility(View.VISIBLE);
            bottom3.setVisibility(View.GONE);
            key_send.setText("发送密码");
        } else if (leixing.equals("2")) {//租户
            bottom2.setVisibility(View.VISIBLE);
            bottom3.setVisibility(View.GONE);
            key_send.setText("设置密码");
        } else {//普通用户
            bottom2.setVisibility(View.INVISIBLE);
            bottom3.setVisibility(View.VISIBLE);
        }
        setStatusBarHeight(v_statusbar);
        if (activity.equals("one")) {
            localKey = KeyFragment.curKeys;
//            key_title.setText(localKey.getLockAlias());
            if (leixing.equals("1") || leixing.equals("3")) {//当该钥匙位用户或者租户用户的话，才显示有效期
                String start = String.valueOf(localKey.getStartDate());
                String end = String.valueOf(localKey.getEndDate());
                if (start != null && end != null) {
                    if (start.equals("0")) {
                        bottom3.setVisibility(View.INVISIBLE);
                    } else {
                        bottom3.setVisibility(View.VISIBLE);
                        shijain_start.setText(TimesUtils.timeStamp2Date(Long.parseLong(start)));
                        shijain_end.setText(TimesUtils.timeStamp2Date(Long.parseLong(end)));
                    }
                }
            }
            if (leixing.equals("2")){
                if (localKey.getReset_rent_pass().equals("1")){
                    try {
                        showTransactionPassword();
                    }catch (Exception e){

                    }

                }
            }

        } else {
            initGreenDao();
            SLock.getServices().login(uid, "itboye");
            kensBean = new ArrayList<>();
            keys = new ArrayList<>();
            showProgressDialog("正在获取钥匙......", false);
            cz=1;
            if ("".equals(sid)){
                keyPresenter.onMyKey(uid, "");
            }else {
                keyPresenter.onMyKey(sid, "");
            }

        }



       // setButtonFocusChanged(icon);
        //登录的广播
        IntentFilter filter2 = new IntentFilter("changeavart");
        registerReceiver(loginReceiver, filter2);
        //退出登录的广播
        IntentFilter filter1 = new IntentFilter(ActivityMyData.AVARTACTION);
        registerReceiver(loginReceivers, filter1);

        //播放音乐的广播
        IntentFilter yinyueFilter = new IntentFilter(KAIMEN);
        registerReceiver(yinyueReceivers, yinyueFilter);

//        rotate = AnimationUtils.loadAnimation(this, R.anim.rotate_anim);
//        LinearInterpolator lir = new LinearInterpolator();
//        rotate.setInterpolator(lir);//设置这个是因为不设置这个图片旋转会出现卡顿现象

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //位置权限申请（蓝牙搜索需要）
            int finePermission = ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION);
            int coarsePermission = ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
            if (finePermission != PackageManager.PERMISSION_GRANTED || coarsePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{
                                Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.ACCESS_COARSE_LOCATION
                        },
                        REQUEST_CODE_PERMISSION
                );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "请同意权限申请！", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }
    }

    BroadcastReceiver loginReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };
    BroadcastReceiver loginReceivers = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            finish();
        }

        ;
    };
    BroadcastReceiver yinyueReceivers = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {

            key_play = (String) SPUtils.get(MyApplcation.ctx, null, SPContants.KEY_PLAY, "");
            if (!key_play.equals("1")) {//播放开门音乐的标志
                MyGongJv.plays("kaimen.mp3");
            }
        }


    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(loginReceiver);
        unregisterReceiver(loginReceivers);
        unregisterReceiver(yinyueReceivers);
        SLock.getServices().disconnectBle();
      //  icon.clearAnimation();
    }

    /**
     * 数据库初始化
     */
    private void initGreenDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "zhujias.db", null);
        Database db = helper.getWritableDb();
        daoSession = new DaoMaster(db).newSession();
        keyDao = daoSession.getKeyDao();
    }

    @Override
    protected void onReadIntent(Bundle bundle) {
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.key_tb:
                if (key_tb.isChecked()) {
                    ByAlert.alert("开门音开启");
                    SPUtils.put(this, null, SPContants.KEY_PLAY, "");//是否播放开锁提示音
                } else {
                    ByAlert.alert("开门音关闭");
                    SPUtils.put(this, null, SPContants.KEY_PLAY, "1");
                }
                break;
            case R.id.key_finish:
                finish();
                break;
            case R.id.key_shezhi:
                PuPoWindow(v);
                break;
            case R.id.icon://开门
                if (localKey == null) {
                    ByAlert.alert("没有获取到锁信息");
                    return;
                }
                if (localKey.getHas_valid_rent().equals("0")) {
                  //  icon.setBackgroundResource(R.drawable.guansuo);
                    clear();
                    Glide.with(KeyGuanLiActivity.this).load(R.drawable.keyfiff)
                            .diskCacheStrategy(DiskCacheStrategy.ALL).into(icon);
//                    if (rotate != null) {
//                        icon.startAnimation(rotate);
//                    } else {
//                        icon.setAnimation(rotate);
//                        icon.startAnimation(rotate);
//                    }
                    showProgressDialog("正在开门,请稍后......", true);
                    if (localKey.getTypes().equals("2")) {//租户开门需要调用单独的开门sdk，可以设置出租模式
                        Calendar calendar = Calendar.getInstance();
                        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 5);//设置当前时间天数加五天
                        long time = calendar.getTimeInMillis();//当前时间加五天
                        if (localKey.getEndDate() * 1000 < time) {//如果结束时间小于当前时间加五天，就传结束时间。反之就传当前时间加五天（租客密码有五天的有效期）
                            SLock.getServices().unLock(localKey.getLockMac(), uid, LockMode.RENT, localKey.getEndDate() * 1000, new UnlockCallback() {
                                @Override
                                public void onBatteryChange(String mac, final int battery) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            power = battery;
                                        }
                                    });
                                }
                            });
                        } else {
                            SLock.getServices().unLock(localKey.getLockMac(), uid, LockMode.RENT, time, new UnlockCallback() {
                                @Override
                                public void onBatteryChange(String mac, final int battery) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            power = battery;
                                        }
                                    });
                                }
                            });
                        }
                    } else {//非租户直接开门
                        SLock.getServices().unLock(localKey.getLockMac(), uid, new UnlockCallback() {
                            @Override
                            public void onBatteryChange(String mac, final int battery) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        power = battery;

                                    }
                                });
                            }
                        });
                    }

                } else {
                    ByAlert.alert("该锁已有合法租户，管理员不能开门");
                }
                break;
            case R.id.key_send_key://发送钥匙
                if (localKey == null) {
                    ByAlert.alert("没有获取到锁信息");
                    return;
                }
                if (localKey.getHas_valid_rent().equals("0")) {
                    intent = new Intent(this, SendKeyActivity.class);
                    intent.putExtra("lockid", localKey.getLockId());
                    intent.putExtra("type", leixing);
                    intent.putExtra("start", localKey.getStartDate());
                    intent.putExtra("end", localKey.getEndDate());
                    startActivity(intent);
                } else {
                    ByAlert.alert("该锁已有合法租户，管理员不能发送钥匙");
                }

                break;
            case R.id.key_send_pass://发送密码
                if (localKey == null) {
                    ByAlert.alert("没有获取到锁信息");
                    return;
                }
//                SLock.getServices().getLockMode(localKey.getLockMac());
//                Log.d("=====lock","");

                if (localKey.getHas_valid_rent().equals("0")) {
//                    SLock.getServices().setRentMode(localKey.getLockMac());

                    if (localKey.getTypes().equals("0")) {//管理员--跳转到发送密码
                        intent = new Intent(this, SendPassActivity.class);
                        intent.putExtra("lockid", localKey.getLockId());
                        intent.putExtra("mac", localKey.getLockMac());
                        intent.putExtra("type",localKey.getTypes());
                        startActivity(intent);
                    } else {//租户--跳转到设置密码
                        intent = new Intent(this, SetPassActivity.class);
                        intent.putExtra("lockid", localKey.getLockId());
                        intent.putExtra("lockMac", localKey.getLockMac());
                        intent.putExtra("end", localKey.getEndDate());
                        startActivity(intent);
                    }
                } else {

                    ByAlert.alert("该锁已有合法租户，管理员不能发送密码");
                }
                break;
            case R.id.key_user://用户管理
                if (localKey == null) {
                    ByAlert.alert("没有获取到锁信息");
                    return;
                }
                intent = new Intent(this, YongHuAdminActivity.class);
                intent.putExtra("lockid", localKey.getLockId());
                intent.putExtra("lockMac", localKey.getLockMac());
                intent.putExtra("type", leixing);
                startActivity(intent);

                break;
            case R.id.key_jilu://开锁记录
                if (localKey == null) {
                    ByAlert.alert("没有获取到锁信息");
                    return;
                }
                intent = new Intent(this, KaiSuoJiLuActivity.class);
                intent.putExtra("keyid", localKey.getKeyId());
                intent.putExtra("lockid", localKey.getLockId());
                startActivity(intent);
                break;

            case R.id.key_tv_mess://消息
                if (activity.equals("one")) {//从锁界面跳转过来，直接返回，跳转到消息界面
                    intent = new Intent();
                    setResult(110, intent);
                    finish();
                } else {//处于锁模式，直接跳转到主界面
                    intent = new Intent(this, MainActivity.class);
                    intent.putExtra("type", "1");
                    startActivity(intent);
                }
                break;
            case R.id.key_tv_jiaozu://交租
                intent = new Intent(this, ActivityMySign.class);
                startActivity(intent);
                break;
            case R.id.key_tv_weixiu://维修
                intent = new Intent(this, ActivityGuanJia.class);
                startActivity(intent);
                break;
            case R.id.key_tv_zhangdan://账单
//                intent = new Intent(this, WebActivity.class);
                intent = new Intent(this,RentingOrderListActivity.class);
                intent.putExtra(
                        "url", NetPublicConstant.WEB_URL02
                                + "/wallet/index?uid="
                                + uid + "&psw=" + (SPUtils.get(this, null, SPContants.PASSWORD, "") + ""));
                intent.putExtra("title", "资金交易明细");
                startActivity(intent);
                break;
            case R.id.set_shezhi://设置
                popupWindow.dismiss();
                intent = new Intent(this, KeySetUpActivity.class);
                intent.putExtra("lockid", localKey.getLockId());
                intent.putExtra("lockAlias", localKey.getLockAlias());
                intent.putExtra("mac", localKey.getLockMac());
                startActivity(intent);
                break;
            case R.id.set_putong://普通模式
                popupWindow.dismiss();
                ByAlert.alert("设置成功");
                SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
                SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
                break;
            case R.id.set_mensuo://门锁模式
                popupWindow.dismiss();
                if (localKey == null) {
                    ByAlert.alert("没有获取到锁信息");
                    return;
                }
                intent = new Intent(this, KeyXuanZeActivity.class);
                startActivityForResult(intent, 101);
                break;
            case R.id.pop_ok://确定--租户重置租户密码
                List<String> passList = new ArrayList<>();
                passList.add("");
                passList.add("");
                passList.add("");
                passList.add("");
                passList.add("");

                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 5);//设置当前时间天数加五天
                long time = calendar.getTimeInMillis();//当前时间加五天
                showProgressDialog("正在重置,请稍后......", false);
                SLock.getServices().setRentMode(localKey.getLockMac(), time,passList);
                break;

        }
    }
    private void clear(){
        icon.setBackgroundResource(0);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == 105) {
            Bundle bundle = data.getExtras();
            String macs = bundle.getString("mac");
            String types = bundle.getString("type");
            leixing = types;
            localKey = (Key) bundle.getSerializable("key");

            key_title.setText(localKey.getLockAlias());

            SPUtils.put(MyApplcation.ctx, null, SPContants.CHANGYONG_MAC, macs);//锁名称
            SPUtils.put(MyApplcation.ctx, null, SPContants.CHANGYONG_TYPE, types);//锁类型
            SPUtils.put(MyApplcation.ctx,null,SPContants.LOCK_TYPE,2);

            ByAlert.alert("设置成功");

            if (types.equals("0")) {//管理员
                bottom2.setVisibility(View.VISIBLE);
                bottom3.setVisibility(View.GONE);
                key_send.setText("发送密码");
            } else if (types.equals("2")) {//租户
                bottom2.setVisibility(View.VISIBLE);
                bottom3.setVisibility(View.GONE);
                key_send.setText("发送密码");
            } else {//普通用户
                bottom2.setVisibility(View.INVISIBLE);
                bottom3.setVisibility(View.VISIBLE);
            }

            if (types.equals("1") || types.equals("3")) {//当该钥匙位用户或者租户用户的话，才显示有效期
                String start = String.valueOf(localKey.getStartDate());
                String end = String.valueOf(localKey.getEndDate());
                if (start != null && end != null) {
                    if (start.equals("0")) {
                        bottom3.setVisibility(View.INVISIBLE);
                    } else {
                        bottom3.setVisibility(View.VISIBLE);
                        shijain_start.setText(TimesUtils.timeStamp2Date(Long.parseLong(start)));
                        shijain_end.setText(TimesUtils.timeStamp2Date(Long.parseLong(end)));
                    }
                }
            }

        }
    }

    String unLockHistory;
    @Override
    public void onSuccess(final ResultData resultData) {
        // log(resultData.getId(), true, resultData.getData());
        try {
            closeProgressDialog();


        } catch (Exception e) {
        }
        sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";

        if (resultData.getId() == ID.UNLOCK_SET_MODE || resultData.getId() == ID.UNLOCK) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ByAlert.alert("门开了");
                //    icon.clearAnimation();
                  //  icon.setBackgroundResource(R.drawable.kaisuogif);
                    clear();
                    Glide.with(KeyGuanLiActivity.this).load(R.drawable.kaisuo)
                            .diskCacheStrategy(DiskCacheStrategy.ALL).into(icon);
                    Intent intent = new Intent(KAIMEN);
                    sendBroadcast(intent);

//                    key_play = (String) SPUtils.get(MyApplcation.ctx, null, SPContants.KEY_PLAY, "");
//                    if (!key_play.equals("1")) {//播放开门音乐的标志
//                        MyGongJv.plays("kaimen.mp3");
//                    }
                }
            });
        }
        if (resultData.getId() == ID.GET_LOCK_MODE){//获取锁模市
            Log.d("=======log","锁模市成功");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String str = resultData.getData();
                    //  ByAlert.alert(str);
                    Log.d("=======log",str);
                }
            });

        }
        if (resultData.getId() == ID.GET_UNLOCK_RECORDS) {//开锁成功之后返回的开锁记录
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    unLockHistory = resultData.getData();
                    cz=2;
                    //  ByAlert.alert(str);
                    if ("".equals(sid)){
                        keyPresenter.onUploadHistoryOfUnlock(uid, localKey.getLockId(), unLockHistory, "1", power);

                    }else {
                        keyPresenter.onUploadHistoryOfUnlock(sid, localKey.getLockId(), unLockHistory, "1", power);

                    }
                }
            });
        }
        if (resultData.getId() == ID.SET_RENT_MODE) {//租户重置密码成功
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    cz=3;
                    if ("".equals(sid)){
                        keyPresenter.onUploadHistoryOfUnlockTwo(uid, localKey.getLockId(), "", "1", "1",power);

                    }else {
                        keyPresenter.onUploadHistoryOfUnlockTwo(sid, localKey.getLockId(), "", "1", "1",power);

                    }
                }
            });
        }
    }

    @Override
    public void onFailed(ResultError resultError) {
        try {
            closeProgressDialog();
            SLock.getServices().disconnectBle();
            clear();
            Glide.with(KeyGuanLiActivity.this).load(R.drawable.guansuo)
                    .diskCacheStrategy(DiskCacheStrategy.ALL).into(icon);
          //  icon.clearAnimation();
        } catch (Exception e) {
        }

        log(resultError.getId(), false, resultError.getErrorCode().toLog());
        Log.d("=======log","锁模市失败");
    }

    private void log(final ID id, final boolean isSuccess, final String log) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isSuccess) {
                    ByAlert.alert(id.name() + ":第2个");
                } else {
                    ByAlert.alert(TostKey.getStamp(log));
                }
            }
        });

    }

    @Override
    public void update(Observable o, Object arg) {
        ResultEntity entity = handlerError(arg);
        if (entity != null) {
                if (entity.getEventType() == KeyTwoPresenter.uploadjilu_success) {//上传开锁记录
                    //   ByAlert.alert(entity.getData());
                } else if (entity.getEventType() == KeyTwoPresenter.uploadjilu_fail) {
                    //   ByAlert.alert(entity.getData());
                    if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                        //切换 锁备用服务器
                        showAlert();
                    }
                } else if (entity.getEventType() == KeyTwoPresenter.uploadjilu_two_success) {//租户重置开锁记录的时候（上传开锁记录）
                    try {
                        passwordPop.dismiss();
                        ByAlert.alert("重置成功，请放心使用");
                        SLock.getServices().disconnectBle();
                    }catch (Exception e){
                    }
                } else if (entity.getEventType() == KeyTwoPresenter.uploadjilu_two_fail) {
                    try {
                        ByAlert.alert("重置失败了");
                        SLock.getServices().disconnectBle();
                    }catch (Exception e){
                    }

                } else if (entity.getEventType() == KeyTwoPresenter.setPower_success) {//设置锁电量
                } else if (entity.getEventType() == KeyTwoPresenter.setPower_fail) {
                } else if (entity.getEventType() == KeyTwoPresenter.myKey_success) {//我的钥匙列表
                    kensBean = (List<KeysBean>) entity.getData();
                    if (kensBean != null) {
                        if (kensBean.size() > 0) {
                            keys.clear();
                            //清空本地并重新保存数据
                            DbService.deleteAllKey();
                            for (int i = 0; i < kensBean.size(); i++) {
                                Key key = new Key();
                                key.setAccessToken(MyPreference.getStr(mContext,
                                        MyPreference.ACCESS_TOKEN));
                                if (kensBean.get(i).getType().equals("0")) {
                                    key.setAdmin(true);
                                } else {
                                    key.setAdmin(false);
                                }
//                                  key.setLockVersion(gson.toJson(kensBean.get(i).getLock_version()));
                                key.setLockName(kensBean.get(i).getLock_name());
                                key.setLockMac(kensBean.get(i).getLock_mac());
                                key.setAdminPs(kensBean.get(i).getAdminPwd());
                                key.setUnlockKey(kensBean.get(i).getLock_key());
                                key.setAdminKeyboardPwd(kensBean.get(i).getNoKeyPwd());
                                key.setDeletePwd(kensBean.get(i).getDeletePwd());
                                key.setPwdInfo("");
                                key.setTimestamp(0);
                                key.setAesKeystr(kensBean.get(i).getAesKeyStr());
                                // key.setTimezoneRawOffset(TimeZone.getDefault().getOffset(currentTimeMillis()));
                                key.setTimezoneRawOffset(Integer.parseInt(get(this, null, SPContants.SHIQU, "") + ""));

                                //上面是开锁用到的必要数据，下面这些是一些操作数据
                                key.setLockId(kensBean.get(i).getLock_id());
                                key.setKeyId(kensBean.get(i).getKey_id());
                                key.setLockAlias(kensBean.get(i).getLock_alias());
                                key.setStartDate(parseLong(kensBean.get(i).getStart()));
                                key.setEndDate(parseLong(kensBean.get(i).getEnd()));

                                key.setUser_type(kensBean.get(i).getUser_type());
                                key.setStatus(kensBean.get(i).getStatus());
                                key.setPush(kensBean.get(i).getPush());
                                key.setHouse_no(kensBean.get(i).getHouse_no());
                                key.setTypes(kensBean.get(i).getType());
                                key.setKeyStatus(kensBean.get(i).getKeyStatus());
                                key.setBattery(kensBean.get(i).getPower());
                                key.setLock_type(kensBean.get(i).getLock_type());
                                key.setHas_valid_rent(kensBean.get(i).getHas_valid_rent());
                                key.setReset_rent_pass(kensBean.get(i).getReset_rent_pass());
                                key.setId(keyDao.insert(key));
                                keys.add(key);

                            }
                            //清空本地并重新保存数据
                            DbService.saveKeyList(keys);

                            for (int i = 0; i < keys.size(); i++) {
                                if (keys.get(i).getLockMac().equals(cy_mac)) {
                                    localKey = keys.get(i);
                                    key_title.setText(localKey.getLockAlias());
                                    if (localKey.getTypes().equals("2")){
                                        if (localKey.getReset_rent_pass().equals("1")){
                                            showTransactionPassword();
                                        }
                                    }
                                    if (leixing.equals("1") || leixing.equals("3")) {//当该钥匙位用户或者租户用户的话，才显示有效期
                                        String start = String.valueOf(localKey.getStartDate());
                                        String end = String.valueOf(localKey.getEndDate());
                                        if (start != null && end != null) {
                                            if (start.equals("0")) {
                                                bottom3.setVisibility(View.INVISIBLE);
                                            } else {
                                                bottom3.setVisibility(View.VISIBLE);
                                                shijain_start.setText(TimesUtils.timeStamp2Date(Long.parseLong(start)));
                                                shijain_end.setText(TimesUtils.timeStamp2Date(Long.parseLong(end)));
                                            }
                                        }
                                    }
                                }
                            }
                            if (localKey == null) {
                                ByAlert.alert("保存的锁不存在了");
                                SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
                                SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
                                Intent intent = new Intent(KeyGuanLiActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            } else {//锁存在的时候   判断异常吗，然后直接跳转到主界面吧
                                String type = localKey.getStatus();
                                if (type.equals("110402") || type.equals("110405") || type.equals("110408") || type.equals("110410")) {
                                    ByAlert.alert("该钥匙处于异常状态");
                                    SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
                                    SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
                                    Intent intent = new Intent(KeyGuanLiActivity.this, MainActivity.class);
                                    intent.putExtra("unlock",type);
                                    startActivity(intent);
                                    finish();
                                }
                                if (localKey.getEndDate() != 0) {
                                    Long dq_time = System.currentTimeMillis() / 1000;//当前时间
                                    Long sx_time = localKey.getEndDate();//锁的实效时间
                                    if (dq_time >= sx_time) {
                                        ByAlert.alert("该钥匙已失效");
                                        SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
                                        SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
                                        Intent intent = new Intent(KeyGuanLiActivity.this, MainActivity.class);
                                        startActivity(intent);
                                        finish();
                                    }
                                }
                            }
                        } else {
                            ByAlert.alert("保存的锁不存在了");
                            SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
                            SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
                            Intent intent = new Intent(KeyGuanLiActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }
                } else if (entity.getEventType() == KeyTwoPresenter.myKey_fail) {
                    if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                        //切换 锁备用服务器
                        showAlert();
                    }else {
                        ByAlert.alert(entity.getMsg());
                    }
                }else  if (entity.getEventType() == HousePresenter.queryRedDot_success){
                    Log.d("hongdian=","true");
                    RedDotBean mRedDotBean= (RedDotBean) entity.getData();
                    showDialog(mRedDotBean);//展示所有弹框
                    saveRedDotData(mRedDotBean);//保存红点数据

                }else if (entity.getEventType() == HousePresenter.queryRedDot_fail){
                    if (entity.getCode().equals("-2")||entity.getMsg().equals("登录已失效，请重新登录")){
                        ByAlert.alert("登录已失效，请重新登录");
                        exit();
                        startActivity(new Intent(this,LoginActivity.class));
                    }
//                Log.d("hongdian=","false");
//                ByAlert.alert("红点数据请求失败");
                }else if (entity.getEventType()==UserPresenter.By_GETSID_success){//获取sid 成功
                    SIDBean data1 = (SIDBean) entity.getData();
                    SPUtils.put(MyApplcation.ctx,null, SPContants.LOCK_SESSION,data1.getSid());
                    SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
                    toRefreshData(data1.getSid());
                }else if (entity.getEventType()==UserPresenter.By_GETSID_fail){
                    ByAlert.alert(entity.getMsg());
                }

        }
        try {
            closeProgressDialog();
            clear();
            Glide.with(KeyGuanLiActivity.this).load(R.drawable.guansuo)
                    .diskCacheStrategy(DiskCacheStrategy.ALL).into(icon);
        } catch (Exception e) {
        }
    }


    private void toRefreshData(String sid) {
        if (cz==1){
            if ("".equals(sid)){
                keyPresenter.onMyKey(uid, "");
            }else {
                keyPresenter.onMyKey(sid, "");
            }
        }else if (cz==2){
            if ("".equals(sid)){
                keyPresenter.onUploadHistoryOfUnlock(uid, localKey.getLockId(), unLockHistory, "1", power);

            }else {
                keyPresenter.onUploadHistoryOfUnlock(sid, localKey.getLockId(), unLockHistory, "1", power);

            }
        }else if (cz==3){
            if ("".equals(sid)){
                keyPresenter.onUploadHistoryOfUnlockTwo(uid, localKey.getLockId(), "", "1", "1",power);

            }else {
                keyPresenter.onUploadHistoryOfUnlockTwo(sid, localKey.getLockId(), "", "1", "1",power);

            }
        }else if (cz==4){//白马锁列表

        }
    }
    /**
     * 钥匙搜索切换框
     */
    private void PuPoWindow(View v) {
        View view = LayoutInflater.from(this).inflate(
                R.layout.item_shezhi, null);
        TextView set_shezhi = (TextView) view
                .findViewById(R.id.set_shezhi);
        TextView set_putong = (TextView) view
                .findViewById(R.id.set_putong);
        TextView set_mensuo = (TextView) view
                .findViewById(R.id.set_mensuo);

        set_shezhi.setOnClickListener(this);
        set_putong.setOnClickListener(this);
        set_mensuo.setOnClickListener(this);
        popupWindow = new PopupWindow(view, FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAsDropDown(v);
    }

    //重置密码的pop
    PopupWindow passwordPop=null;

    //重置密码的pop
    public void showTransactionPassword() {
       final View contentView = LayoutInflater.from(this)
                .inflate(R.layout.popwindow_transformation_sure, null);
        passwordPop = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        TextView pop_ok = (TextView) contentView.findViewById(R.id.pop_ok);
        pop_ok.setOnClickListener(this);
        // passwordPop.setAnimationStyle(R.style.popupwindow_anim_style);
        //passwordpop 可点击
        passwordPop.setFocusable(true);

        contentView.setFocusable(true);//comment by danielinbiti,设置view能够接听事件，标注1
        contentView.setFocusableInTouchMode(true); //comment by danielinbiti,设置view能够接听事件 标注2
        //点击手机返回键pop关闭
        contentView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    if (passwordPop != null) {
                        passwordPop.dismiss();
                        KeyGuanLiActivity.this.finish();
                    }
                }
                return false;
            }
        });
        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                passwordPop.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
            }
        });
    }

    //显示dialog
    public  void showDialog(RedDotBean mRedDotBean){
        //dialog type  1  尚有租金逾期未交  2 尚有附件清单未确认 3 尚有未完成的签约 4 尚有申请签约的房源

        if (MyApplcation.mShenQin==null){
            //经纪人去选租客
            if (mRedDotBean.getApply_list().size()>0){
                MyApplcation.mShenQin= new ListDialog(
                        KeyGuanLiActivity.this,
                        "尚有申请签约的房源",
                        mRedDotBean.getApply_list(),
                        4);
                MyApplcation.mShenQin.getDialog_cancelImg().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MyApplcation.mShenQin.cancel();
                        MyApplcation.mShenQin=null;
                    }
                });
                if (mRedDotBean.getApply_list().size()>12){
                    MyApplcation.mShenQin.setListDialogHeigh();
                }
                MyApplcation.mShenQin.show();
            }
        }

        if (MyApplcation.mQianDing==null){
            //租客签订合同
            if (mRedDotBean.getNeed_sign_contract_list().size()>0){
                MyApplcation.mQianDing= new ListDialog(
                        KeyGuanLiActivity.this,
                        "尚有未完成的签约",
                        mRedDotBean.getNeed_sign_contract_list(),
                        3);

                MyApplcation.mQianDing.getDialog_cancelImg().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MyApplcation.mQianDing.cancel();
                        MyApplcation.mQianDing=null;
                    }
                });
                if (mRedDotBean.getNeed_sign_contract_list().size()>12){
                    MyApplcation.mQianDing.setListDialogHeigh();
                }
                MyApplcation.mQianDing.show();
            }
        }

        if (MyApplcation.mFujian==null){
            //租客确定附件单
            if (mRedDotBean.getNeed_confirm_facility_list().size()>0){
                List<String> confirm = new ArrayList<>();
                List<String> contract_no = new ArrayList<>();
                for (int i=0;i< mRedDotBean.getNeed_confirm_facility_list().size();i++){
                    contract_no.add(mRedDotBean.getNeed_confirm_facility_list().get(i).getContract_no());
                    confirm.add(getStringContent(mRedDotBean.getNeed_confirm_facility_list().get(i)));
                }

                MyApplcation.mFujian= new ListDialog(
                        KeyGuanLiActivity.this,
                        "尚有附件清单未确认",
                        confirm,
                        2,contract_no);
                MyApplcation.mFujian.getDialog_cancelImg().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MyApplcation.mFujian.cancel();
                        MyApplcation.mFujian=null;
                    }
                });
                if (mRedDotBean.getNeed_confirm_facility_list().size()>2){
                    MyApplcation.mFujian.setListDialogHeigh();
                }
                MyApplcation.mFujian.show();
            }
        }
        if (MyApplcation.mYuQi==null){

            //租客逾期支付
            if (mRedDotBean.getOverdue_list().size()>0){
                MyApplcation.mYuQi= new ListDialog(
                        KeyGuanLiActivity.this,
                        "尚有租金逾期未交",
                        mRedDotBean.getOverdue_list(),
                        1);
                MyApplcation.mYuQi.getDialog_cancelImg().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MyApplcation.mYuQi.cancel();
                        MyApplcation.mYuQi=null;
                    }
                });
                if (mRedDotBean.getOverdue_list().size()>12){
                    MyApplcation.mYuQi.setListDialogHeigh();
                }
                MyApplcation.mYuQi.show();
            }
        }
    }

    //存储红点
    public  void saveRedDotData(RedDotBean mRedDotBean) {
        // ImageView key_img_mess, key_img_jiaozu, key_img_weixiu, key_img_zhangdan;//消息，交租，维修，账单消息 红点显示
        if (mRedDotBean.getNeed_write_facility_count()>0){ //需要填写附件单的合同数
            SPUtils.put(KeyGuanLiActivity.this,null,SPContants.FUJIAN_ORDER,true);
        }
        //消息
        updateRedDot(key_img_mess,mRedDotBean.getUnread_count().getTotal());
        //交租
        updateRedDot(key_img_jiaozu,mRedDotBean.getOverdue_count());
        //维修
        updateRedDot(key_img_weixiu,mRedDotBean.getRepair_count());
        //账单
        updateRedDot(key_img_zhangdan,mRedDotBean.getBill_count());


        SPUtils.put(KeyGuanLiActivity.this,null,SPContants.TOTAL_MESSAGE,mRedDotBean.getUnread_count().getTotal());//消息总数
        SPUtils.put(KeyGuanLiActivity.this,null,SPContants.SYSTEM_MESSAGE,mRedDotBean.getUnread_count().getSystem());//系统消息
        SPUtils.put(KeyGuanLiActivity.this,null,SPContants.CONTRANCT_MESSAGE,mRedDotBean.getUnread_count().getContract());//签约消息
        SPUtils.put(KeyGuanLiActivity.this,null,SPContants.LOCK_MESSAGE,mRedDotBean.getUnread_count().getLock());//锁消息
        SPUtils.put(KeyGuanLiActivity.this,null,SPContants.REPAIR_COUNT,mRedDotBean.getRepair_count());//未维修数
        SPUtils.put(KeyGuanLiActivity.this,null,SPContants.BILL_COUNT,mRedDotBean.getBill_count());//账单数
    }


    //是否显示红点
    public void updateRedDot(ImageView imageView,int count){

        if (count>0){
           imageView.setVisibility(View.VISIBLE);
        }else {
            imageView.setVisibility(View.GONE);
        }
    }

}
